<template>
  <div class="md-material-select-base">
    <!--单张图片-->
    <div class="container" v-if="type==='img'">
      <div class="cover cover-img" :style="{width: config.width || '121px', height: config.height || '200px', lineHeight: config.height || '200px'}">

        <span v-if="!value" class="label">
          未设置
        </span>

        <img v-if="value" :src="value" />

        <div class="cover-mask" @click="handleShowDialog()">
          <span>{{value?'更换':'去设置'}}</span>
        </div>
      </div>

      <div class="cover-btn">
        <span @click="handleDefault()">默认</span>
        <span v-if="value" @click="handleClear()">清除</span>
      </div>
    </div>
    <!--活动模板-->
    <div class="container" v-if="type==='temp'">
      <div class="cover cover-img" :style="{width: config.width || '121px', height: config.height || '200px', lineHeight: config.height || '200px'}">

        <span v-if="!value" class="label">
          未设置
        </span>

        <img v-if="value" :src="value" />

        <div class="cover-mask" @click="handleShowDialog()">
          <span>{{value?'更换':'去设置'}}</span>
        </div>
      </div>
    </div>
    <!--音乐-->
    <div class="container" v-if="type==='music'">
      <div class="cover cover-img" :style="{width: config.width || '121px', height: config.height || '200px', lineHeight: config.height || '200px'}">

        <span v-if="!value" class="label">
          <img src="../../../assets/img/icon-music1.png" style="width: 30px !important" />未设置
        </span>

        <p v-if="value">
          <img src="../../../assets/img/icon-music.png" />
          <audio :src="value" :ref="`music`" controls v-show="false"></audio>
        </p>

        <div class="cover-mask" @click="handleShowDialog()">
          <span>{{value?'更换':'去设置'}}</span>
        </div>
      </div>

      <div class="cover-btn">
        <span @click="handlePause()" v-if="value">
          <i class="el-icon" :class="[isPlay?'el-icon-video-pause':'el-icon-video-play']"></i>
        </span>
        <span @click="handleDefault()">默认</span>
        <span v-if="value" @click="handleClear()">清除</span>
      </div>
    </div>
    <!--轮播图-->
    <div class="container container-banner" v-if="type==='banner'">
      <div class="cover cover-banner-item" v-for="item in value" :key="item.id" :style="{width: config.width || '121px', height: config.height || '200px', lineHeight: config.height || '200px'}">
        <img :src="item.cover" />

        <el-popover placement="bottom" width="350" trigger="hover" popper-class="md-upload-img-popover">

          <div class="cover-mask" slot="reference" @click="handleShowDialog(item)" :style="{width: config.width || '121px', height: config.height || '200px', lineHeight: config.height || '200px'}">
            <span>更换轮播图</span>
            <i class="el-icon-delete" @click.stop="handleDelete(item)"></i>
          </div>

          <div class="md-upload-form-item">
            <label class="md-upload-form-item-label">跳转网址：</label>
            <div class="md-upload-form-item-content">
              <el-input v-model="item.url" placeholder="点击轮播图要跳转的网址" type="textarea" @blur="handleWebURLBlur" />
            </div>
          </div>
        </el-popover>

      </div>

      <div class="cover cover-img" :style="{width: config.width || '121px', height: config.height || '200px', lineHeight: config.height || '200px'}">

        <span class="label" @click="handleShowDialog()">
          <i class="el-icon-plus"></i>
          <p>添加封面</p>
        </span>

      </div>
    </div>
    <!--单文件上传-->
    <div class="container container-singleimg" v-if="type==='singleimg'">
      <div class="cover cover-img" :style="{width: config.width || '121px', height: config.height || '200px', lineHeight: config.height || '200px'}">

        <span v-if="!value" class="label">
          未设置
        </span>

        <img v-if="value" :src="value" />

        <div class="cover-mask">
          <div class="md-upload">
            <el-upload :action="action" ref="singleimg" name="file" :headers="headers" :before-upload="handleBeforeUpload" :show-file-list="false" :on-success="handleUploadSuccess" :limit="1">
              <p>
                <span>{{value?'更换':'去设置'}}</span>
                <span v-if="fileSize">{{fileSize}}</span>
                <span v-if="uploadSize">{{uploadSize}}</span>
              </p>
            </el-upload>
          </div>
        </div>
      </div>

      <div class="cover-btn">
        <span @click="handleDefault()">默认</span>
        <span v-if="value" @click="handleClear()">清除</span>
      </div>
    </div>
    <el-dialog custom-class="md-material-select-dialog" :visible.sync="dialogVisible" :width="config.dialogWidth || '50%'" append-to-body :close-on-click-modal="false" :close-on-press-escape="false" :before-close="handleBeforeClose">
      <component :is="component" ref="md-resource" @selected="handleSelect" :height="config.dialogHeight || '480px'" :params="{...params,tempUrl:type==='temp'?value:''}"></component>
    </el-dialog>
  </div>
</template>

<script>
import { mdApiBase } from '../../../ddd/config.service'
export default {
  name: 'MdMaterialSelectBaseComponent',
  props: {
    /**
     * 动态组件
     */
    component: null,
    /**
     * 值
     */
    value: {
      type: [String, Array, Object],
      default: null
    },
    /**
     * 文件尺寸 100*100
     */
    fileSize: {
      type: String,
      default: null
    },
    /**
     * 文件上传大小
     */
    uploadSize: {
      type: String,
      default: null
    },
    /**
     * 动态组件内参数
     */
    params: {
      type: Object,
      default: () => {}
    },
    config: {
      type: Object,
      default: () => {
        return {
          /**
           * 图片容器宽度
           */
          width: '121px',
          /**
           * 图片容器高度
           */
          height: '200px',
          /**
           * 弹窗宽度
           */
          dialogWidth: '50%',
          /**
           * 弹窗内容高度（非弹窗高度）
           */
          dialogHeight: '480px'
        }
      }
    },
    /**
     * 组件类型：img、music、banner、singeimg
     */
    type: {
      type: String,
      default: 'img'
    }
  },
  data() {
    return {
      dialogVisible: false,
      bannerList: [],
      isPlay: false,
      action: `${mdApiBase}/common/upload`,
      headers: {
        Authorization: this.$local.getItem('Authorization')
      }
    }
  },
  watch: {
    value: {
      handler: function (val) {
        if (val) {
          this.bannerList = val
        }
      },
      deep: true
    }
  },
  methods: {
    // 选择物料
    handleSelect(event) {
      if (this.type === 'banner') {
        if (this.bannerCurrent) {
          // 更换轮播图
          const bannerList = JSON.parse(JSON.stringify(this.bannerList))
          const bannerIndex = bannerList.findIndex((e) => this.handleGetFileName(e.cover) === this.handleGetFileName(this.bannerCurrent.cover))

          if (bannerIndex > -1) {
            bannerList[bannerIndex].cover = event.content
          }

          const newBannerList = [
            ...new Set([
              ...bannerList.map((m) => {
                return m.cover
              })
            ])
          ]

          if (newBannerList.length !== this.bannerList.length) {
            this.$message.error('轮播图已被占用')
            return
          } else {
            this.bannerList = bannerList
            this.$emit('input', this.bannerList)
            this.$emit('change', this.bannerList)
            this.bannerCurrent = null
            this.dialogVisible = false
          }
        } else {
          // 添加轮播图
          const bannerList = JSON.parse(JSON.stringify(this.bannerList))
          const bannerIndex = bannerList.findIndex((e) => this.handleGetFileName(e.cover) === this.handleGetFileName(event.content))
          if (bannerIndex > -1) {
            this.$message.error('轮播图已被占用')
            return
          } else {
            this.bannerList.push({ id: `banner_${this.bannerList.length + 1}`, cover: event.content, url: null })
            this.$emit('input', this.bannerList)
            this.$emit('change', this.bannerList)
            this.bannerCurrent = null
            this.dialogVisible = false
          }
        }
      } else {
        this.$emit('input', event.content)
        this.$emit('change', event)
        this.bannerCurrent = null
        if (event.operation === 'custom') {
          this.dialogVisible = false
        }
      }
    },
    // 根据文件地址获取文件名称
    handleGetFileName(url) {
      const arr = url.split('/')
      const lastLen = arr.length - 1
      return arr[lastLen]
    },
    // 跳转网址发生改变事件
    handleWebURLBlur() {
      this.$emit('input', this.bannerList)
      this.$emit('change', this.bannerList)
    },
    // 删除轮播图
    handleDelete(item) {
      const bannerList = this.bannerList
      const bannerIndex = this.bannerList.findIndex((e) => e.id === item.id)
      bannerList.splice(bannerIndex, 1)
      this.bannerList = bannerList
      this.$emit('input', this.bannerList)
      this.$emit('change', this.bannerList)
    },
    // 显示物料弹窗
    handleShowDialog(item) {
      if (item) {
        this.bannerCurrent = item
        this.$emit('before', this.params)
        this.dialogVisible = true
      } else {
        this.$emit('before', this.params)
        this.dialogVisible = true
      }
    },
    // 上传文件
    handleBeforeUpload() {
      return true
    },
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.$emit('input', res.url)
        this.$emit('change', res.url)

        this.$refs['singleimg'].clearFiles()

        return
      }

      if (res.code === 401) {
        this.$local.clear()
        this.$message.error('登录超时')
        this.$router.push('/login')
        return
      }

      this.$message.error(res.msg)
    },
    // 默认
    handleDefault() {
      this.$emit('default', this.params)
    },
    // 清除
    handleClear() {
      this.$emit('clear', this.params)
    },
    // 音乐开关
    handlePause() {
      if (!this.isPlay) {
        this.$refs['music'].play()
        this.isPlay = true
      } else {
        this.$refs['music'].pause()
        this.isPlay = false
      }
    },
    // 弹窗关闭前处理
    handleBeforeClose(done) {
      if (this.params) {
        if (this.params.type1 && this.params.type1 === 5) {
          this.$refs['md-resource'].handleCloseAllMusic()
          done()
          return
        } else {
          done()
        }
      }

      done()
    }
  }
}
</script>

<style lang="less" scoped>
.md-material-select-base {
  width: 100%;
  box-sizing: border-box;
  .container {
    display: flex;
    align-items: center;
    .cover {
      background-color: rgba(0, 0, 0, 0.06);
      text-align: center;
      color: #999;
      cursor: pointer;
      position: relative;
      img {
        width: auto;
        height: auto;
        max-width: 100%;
        max-height: 100%;
      }
      .cover-mask {
        display: none;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.1);
        color: #fff;
        position: absolute;
        top: 0px;
        left: 0px;
      }
      &:hover {
        .cover-mask {
          display: block;
        }
        .label {
          display: none;
        }
      }
    }
    .cover-btn {
      flex: 1;
      margin-left: 20px;
      display: flex;
      align-items: center;

      span {
        color: @md-primary-color;
        cursor: pointer;
        margin-right: 20px;
        i {
          display: block;
          font-size: 20px;
        }
        &:last-child {
          margin-right: 0px;
        }
      }
    }
    &.container-banner {
      display: flex;
      flex-wrap: wrap;
      .cover {
        line-height: normal !important;
        background-color: transparent;
        border: 1px dashed #e8e5e5;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
        margin-bottom: 20px;
        &.cover-banner-item {
          background-color: rgba(0, 0, 0, 0.06);
        }
        .cover-mask {
          display: none;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.1);
          color: #fff;
          position: absolute;
          top: 0px;
          left: 0px;
          z-index: 9;
          i {
            position: absolute;
            right: 20px;
            top: 10px;
            z-index: 10;
          }
        }
        img {
          width: auto;
          height: auto;
          max-width: 100%;
          max-height: 100%;
        }
        .label {
          i {
            font-size: 25px;
          }
          p {
            margin-top: 10px;
          }
        }
        &:hover {
          .cover-mask {
            display: block;
          }
          .label {
            display: block;
          }
        }
      }
    }
    &.container-singleimg {
      .cover {
        .cover-mask {
          .md-upload {
            width: 100%;
            height: 100%;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            ::v-deep .el-upload {
              display: block !important;
              width: 100%;
              height: 70px !important;
              line-height: 22px !important;
              p {
                span {
                  display: block;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
